package radio.vnmedia.vn.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HTMLRegex {

	private Pattern m_pattern;
	private Matcher m_matcher;
	private int m_start_find_index;
	private String mContent;
	
	/**
	 * 
	 * @param content html content
	 * @param pattern string regular expression
	 * @throws Exception
	 */
	public HTMLRegex(String content, String pattern) throws Exception {
		m_pattern = Pattern.compile(pattern);

		m_matcher = m_pattern.matcher(mContent = content);
		m_start_find_index = 0;
	}
	

	/**
	 * Set new pattern and recompile on the old content At the point only one
	 * call updateContent(String content) or setPattern(String pattern) If you
	 * want update both content and pattern then must re-init a new object
	 * 
	 * @param pattern
	 *            new pattern
	 */
	public void setPattern(String pattern) {
		m_pattern = Pattern.compile(pattern);
		m_matcher = m_pattern.matcher(mContent);
		m_start_find_index = 0;
	}

	/**
	 * Update new content and re-match on the old pattern string. At the point
	 * only one call updateContent(String content) or setPattern(String pattern)
	 * If you want update both content and pattern then must re-init a new
	 * object
	 * 
	 * @param content
	 *            new content
	 */
	public void updateContent(String content) {
		m_matcher = m_pattern.matcher(mContent = content);
		m_start_find_index = 0;
	}

	public String getPattern() {
		return m_pattern.pattern();
	}

	public boolean next() {
		return m_matcher.find(m_start_find_index);
	}

	public String getGroup(int group_index) {
		String result = m_matcher.group(group_index);
		m_start_find_index = m_matcher.end();
		return result;
	}

	public String getGroup() {
		String result = m_matcher.group();
		m_start_find_index = m_matcher.end();
		return result;
	}
}
